#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
// 客户端程序
int main(int argc, char const *argv[])
{
    int sfd, ret;
    int length;
    ssize_t sbytes = 0, rbytes = 0;
    char buffer[]  = "hello,server";
    char *pbuffer = NULL;
    struct sockaddr_in svr_addr;
    sfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sfd == -1) {
        perror("socket error");
        exit(EXIT_FAILURE);
    }
    bzero(&svr_addr, sizeof(struct sockaddr_in));
    svr_addr.sin_family = AF_INET;
    svr_addr.sin_port = htons(atoi(argv[2]));
    svr_addr.sin_addr.s_addr = inet_addr(argv[1]);

    // 链接
    ret = connect(sfd, (const struct sockaddr *)&svr_addr, sizeof(struct sockaddr_in));
    if (ret == -1) {
        perror("connect error");
        exit(EXIT_FAILURE);
    }

    // 发送数据采用分两次发送， 一次发送数据长度， 第二次发送数据
    for(;;) {
        length = strlen(buffer);
        pbuffer = (char *) malloc(length + 4);
        // 初始化pbuffer
        memcpy(pbuffer, &length, 4); // 拷贝4个字节长度 数据内容为数据长度
        memcpy(pbuffer + 4, buffer, length);// 四个字节之后是数据内容
        sbytes = send(sfd, pbuffer, length + 4, 0);
        if (sbytes == -1) {
            perror("send error");
            exit(EXIT_FAILURE);
        }
        usleep(100);
    }

    return 0;
}
